package com.blog.blog.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.Customizer;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.web.cors.CorsConfigurationSource;

/**
 * Spring Security配置
 */
@Configuration
@EnableWebSecurity
public class SecurityConfig {

    private final CorsConfigurationSource corsConfigurationSource;

    public SecurityConfig(CorsConfigurationSource corsConfigurationSource) {
        this.corsConfigurationSource = corsConfigurationSource;
    }

    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        http
            // 禁用CSRF（前后端分离项目通常禁用）
            .csrf(csrf -> csrf.disable())
            
            // 配置CORS
            .cors(cors -> cors.configurationSource(corsConfigurationSource))
            
            // 配置请求授权
            .authorizeHttpRequests(auth -> auth
                // 健康检查端点
                .requestMatchers("/actuator/**").permitAll()
                
                // API文档相关
                .requestMatchers("/v3/api-docs/**", "/swagger-ui/**", "/swagger-ui.html", "/api-docs/**").permitAll()
                .requestMatchers("/webjars/**").permitAll()
                
                // 认证相关接口
                .requestMatchers("/api/auth/**").permitAll()
                
                // 公开访问的接口
                .requestMatchers("/api/articles/**").permitAll()
                .requestMatchers("/api/categories/**").permitAll()
                .requestMatchers("/api/tags/**").permitAll()
                .requestMatchers("/api/resume/public/**").permitAll()
                .requestMatchers("/sitemap.xml").permitAll()
                .requestMatchers("/robots.txt").permitAll()
                
                // 国际化接口
                .requestMatchers("/api/i18n/**").permitAll()
                
                // 其他请求需要认证（通过拦截器处理）
                .anyRequest().permitAll()
            );
        
        return http.build();
    }
}


